<template>
  <el-main>
    <!-- 查询条件 -->
    <!-- <div style="overflow: hidden; ">
      <div style="float: left;">
        <el-form
          :model="searchModel"
          ref="searchForm"
          label-width="80px"
          :inline="true"
          size="small"
        >
          <el-form-item>
          <el-input v-model="searchModel.bbmc" placeholder="请输入报表名称" />
          </el-form-item>
          <el-form-item>
          <el-button
              type="primary"
              icon="el-icon-search"
              @click="search(pageNo, pageSize)"
              >查询</el-button
          >
          <el-button icon="el-icon-refresh-right" @click="resetValue()"
              >重置</el-button
          >
          
          </el-form-item>
        </el-form>
      </div>
    </div> -->
    <!-- 数据表格 -->
    <el-table
      :data="dtbbList"
      :height="tableHeight"
      border
      indent="30"
      stripe
      style="width: 100%; margin-bottom: 10px"
      row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <!-- <el-table-column prop="id" label="报表ID" align="center"></el-table-column> -->
      <!-- <el-table-column prop="bblx" label="报表类型" align="center"></el-table-column> -->
      <el-table-column prop="bbmc" label="报表名称"></el-table-column>
      <el-table-column prop="parentName" label="审核状态" align="center">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.approveBz" placement="right" effect="light" :disabled="!scope.row.approveBz">
            <el-badge :is-dot="scope.row.approveBz!=''&&scope.row.approveBz!=null" class="item">
              <el-tag :class="scope.row.approveBz?'tagstyle':''"
              v-if="scope.row.bblx == 1"
              :type="
                scope.row.approveStatus == '5'
                ?'success'
                :scope.row.approveStatus == '4'
                  ? 'danger'
                  : scope.row.approveStatus == '3'
                    ? ''
                    :scope.row.approveStatus == '2'
                      ? 'danger'
                      :scope.row.approveStatus == '1'
                        ? 'warning'
                        :'info'"
                disable-transitions>{{
                scope.row.approveStatus == '5'
                ?'管理部通过'
                :scope.row.approveStatus == '4'
                  ? '管理部未通过'
                  : scope.row.approveStatus == '3'
                    ? '作业区通过待管理部审核'
                    :scope.row.approveStatus == '2'
                      ? '作业区未通过'
                      :scope.row.approveStatus == '1'
                        ? '已上报待作业区审核'
                        :'待上报'
              }}</el-tag>
            </el-badge>
          </el-tooltip>
            
          </template>
      </el-table-column>
      <!-- <el-table-column prop="parentName" label="所属报表" align="center"></el-table-column> -->
      <!-- <el-table-column prop="sjfwIndexId" label="数据服务" align="center"></el-table-column> -->
      <el-table-column label="操作" width="350px">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-edit"
            type="primary"
            size="small"
            plain
            @click="handleEdit(scope.row)"
            >编辑
          </el-button>   
          <el-button
            icon="el-icon-delete"
            type="danger"
            size="small"
            plain
            @click="handleDelete(scope.row)"
            >删除
          </el-button>
          <el-button
            v-if="(scope.row.approveStatus == 0 && scope.row.bblx== 1 && leve == 10) || (scope.row.approveStatus == 2 && leve == 10) || (scope.row.approveStatus == 4 && leve == 10)"
            icon="el-icon-top"
            type="success"
            size="small"
            plain
            @click="handSubmit(scope.row)"
            >上报
          </el-button>
          <el-button
            v-if="(scope.row.approveStatus == 1 && scope.row.bblx== 1 && leve == 100) || (scope.row.approveStatus == 3 && scope.row.bblx== 1 && leve == 1000)"
            icon="el-icon-s-claim"
            type="success"
            size="small"
            plain
            @click="handAudit(scope.row)"
            >审核
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页工具栏 -->
    <!-- <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNo"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="10"
      layout="->,total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination> -->
    <!-- 添加和修改角色窗口 -->
    <system-dialog
      :title="bbmbDialog.title"
      :visible="bbmbDialog.visible"
      :width="bbmbDialog.width"
      :height="bbmbDialog.height"
      @onClose="onClose"
      @onConfirm="onConfirm"
      >
      <div slot="content">
          <el-form
          :model="bbmb"
          ref="bbmbForm"
          :rules="rules"
          label-width="80px"
          :inline="false"
          size="small"
          >
          <!-- <el-form-item label="报表名称" prop="id">
              <el-input v-model="bbmb.id"></el-input>
          </el-form-item> -->
          <el-form-item label="所属报表" prop="parentName">
            <el-input
              v-model="bbmb.parentName"
              @click.native="selectDepartment()"
              :readonly="true"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="报表类型:" prop="bblx">
            <el-select v-model="bbmb.bblx" placeholder="请选择报表分类" clearable="">
              <el-option
                  v-for="(item) in flList"
                    :key="item.id"
                    :label="item.bbmc"
                    :value="item.id"
                  
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="报表名称" prop="bbmc">
              <el-input v-model="bbmb.bbmc"></el-input>
          </el-form-item>
          </el-form>
      </div>
    </system-dialog>
     <!-- 选择所属部门的窗口 -->
     <system-dialog
      :title="parentDialog.title"
      :visible="parentDialog.visible"
      :width="parentDialog.width"
      :height="parentDialog.height"
      @onClose="parentOnClose"
      @onConfirm="parentOnConfirm"
    >
      <div slot="content">
        <el-tree
          ref="parentTree"
          :data="treeList"
          node-key="id"
          :props="defaultProps"
          empty-text="暂无数据"
          :default-expand-all="true"
          :highlight-current="true"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        >
          <div class="customer-tree-node" slot-scope="{ node, data }">
            <span v-if="data.children.length === 0">
              <i class="el-icon-document"></i>
            </span>
            <span v-else @click="changeOpenIcon(data)">
              <svg-icon v-if="data.open" icon-class="add-s" />
              <svg-icon v-else icon-class="sub-s" />
            </span>
            <span style="margin-left: 5px">{{ node.label }}</span>
          </div>
        </el-tree>
      </div>
    </system-dialog>

    <!--预览窗口-->
    <el-dialog :visible.sync="previewFile" width="1000px">
      <div class="tablestyle" id="table" >
          <table border="1" v-if="tableau" style="border-collapse: collapse">
          <tr v-for="(item, index) in tableau" :key="index">
              <td v-for="(item1, index1) in item" :key="index1">{{ item1 }}</td>
          </tr>
          </table>
      </div>
    </el-dialog>

    <!-- 弹出框 -->
    <el-dialog title="报表审核" :visible.sync="dialogFormVisible" custom-class="saveAsDialog2">
      <el-form :inline="true" :model="bbsh" class="demo-form-inline" ref="bbsh" label-position="left" label-width="80px">
        <el-form-item label="审核:" >
          <el-select v-model="bbsh.approveStatus" placeholder="请选择审核状态">
            <!-- syjForm.approveStatus=='0'? syjForm.approveStatus == '未审核':syjForm.approveStatus=='1'?syjForm.approveStatus == '通过':syjForm.approveStatus == '不通过' -->
            <!-- <el-option label="未审核" value="1"></el-option> -->
            <el-option label="通过" :value="leve==100?3:5"></el-option>
            <el-option label="不通过" :value="leve==100?2:4"></el-option>
          </el-select>
        </el-form-item>

        <el-row>
            <el-form-item label="审核备注:">
              <el-input type="textarea" v-model="bbsh.approveBz" placeholder="请输入审核备注"></el-input>
            </el-form-item>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="shclose('bbsh')">取 消</el-button>
        <el-button type="primary" @click="submitForm('bbsh')">确 定</el-button>
      </div>
      </el-dialog>
  </el-main>
</template>

<script>
import axios from "axios";
import XLSX from 'xlsx';
import dtbbApi from '@/api/dtbb/bbmb';
import sjzdApi from '@/api/dtbb/sjzd';
import infoApi from '@/api/dtbb/info';
import { getToken } from "@/utils/auth";
import bbmbApi from "@/api/dtbb/bbmb";
import SystemDialog from "@/components/system/SystemDialog.vue";

// 导入末级节点脚本
import leafUtils from "@/utils/leaf";

export default {
  name: "dtbbList",
  components: { SystemDialog },
  data() {
    return {
      leve:'',//获取用户级别
      //查询条件
      searchModel: {
        bbmc: "",
        pageNo: 1,
        pageSize: 10,
      },
      dtbbList: [], //数据列表
      tableHeight: 0, //表格高度
      pageNo: 1, //当前页码
      pageSize: 10, //每页显示数量
      total: 0, //总数量
      rules: {
        id: [
          { required: true, trigger: "blur", message: "请输入报表ID" },
        ],
        parentName: [
          { required: true, trigger: "blur", message: "请选择所属部门" },
        ],
        bbmc: [
          { required: true, trigger: "blur", message: "请输入报表名称" },
        ],
      },
      current:'',//当前行
      //添加和修改角色窗口属性
      bbmbDialog: { title: "", visible: false, height: 230, width: 500 },
      //角色对象
      bbmb: {
        pid:"",
        id: "",
        bbdm: "",
        bblx: "",
        bbmc: "",
        parentName:"",
        sjfwIndexId:"",
        approveBz:"",
        approveStatus:"",
      },
      //审核信息对象
      bbsh:{
        id: "",
        approveBz:"",
        approveStatus:"",
      },
      //分配权限窗口属性
      dialogVisible: false,
      //审核窗口
      dialogFormVisible: false,
      saveAsDialog2:'',
      bbform:{
          id:'',
          zd:'',
      },
      //下拉框列表数据
      bbList: [],
      zdList: [],
      sjzdList: [],
      //选择字段的对象list
      afterList:[],
      //tia
      infodata:'',
      //
      infoForm:{
          bbid:'',
          cj:'',
          pid:'',
          szgs:'1',
          lxh:'',
          lmc:'',
      },
      //预览
      previewFile:false,
      workbook:'',
      cardActive:'',
      tableau:'',
      //获取报表分类列表0
      flList:[],
      //所属部门窗口属性
      parentDialog: {
        title: "选择所属报表类型",
        visible: false, //是否显示
        width: 300,
        height: 400,
      },
      //树形菜单列表
      treeList: [],
      defaultProps: { children: "children", label: "bbmc" },
    };
  },
  methods: {
    /*** 查询 */
    async search(pageNo = 1, pageSize = 10) {
      this.searchModel.pageNo = pageNo; //当前页码
      this.searchModel.pageSize = pageSize; //每页显示数量
      //发送查询请求
      let res = await bbmbApi.getTreeList(this.searchModel);
      //执行成功
      if (res.success) {
        console.log(res.data);
        //报表列表
        this.dtbbList = res.data;
        //总数量
        this.total = res.data.total;
      }
    },
    //查询报表分类 
    // async search() {
    //   // this.pageNo = pageNo; //当前页码
    //   // this.pageSize = pageSize; //每页显示数量
    //   //发送查询请求
    //       // let res = await fdfxtApi.getFdfxtList(this.pageNo,this.pageSize,this.approveStatus,this.searchDate[0],this.searchDate[1]);
    //       let res = await xjbbApi.getList({bblx:'0'});
    //       //判断是否成功
    //       if(res.success){
    //           console.log(res.data);
    //           console.log(11111);
    //           //赋值
    //           //this.tableData = res.data.records;
    //           //总数量
    //           //this.total = res.data.total;
    //           //console.log(this.total);
    //           this.flList = res.data.records;    
    //           console.log(this.flList);
    //           console.log(10);
    //       }
    //   },
    /*** 重置查询条件 */
    resetValue() {
      //清空查询条件
      this.searchModel.bbmc = "";
      //重新查询
      this.search();
    },
    /*** 打开添加窗口 */
    openAddWindow() {
      this.$resetForm("bbmbForm", this.bbmb); //清空表单数据
      this.bbmbDialog.title = "新增报表模板"; //设置窗口标题
      this.bbmbDialog.visible = true; //显示窗口
    },
    /*** 打开选择所属部门的窗口 */
    async selectDepartment() {
      //显示窗口
      this.parentDialog.visible = true;
      //查询部门列表
      // let res = await departmentApi.getParentTreeList();
      let res = await bbmbApi.getTreeList();
      //判断是否成功
      if (res.success) {
        //赋值
        this.treeList = res.data;
      }
    },
    /*** 选择所属部门取消事件 */
    parentOnClose() {
      this.parentDialog.visible = false;
    },
    /*** 选择所属部门确认事件 */
    parentOnConfirm() {
      this.parentDialog.visible = false;
    },
    // 树节点点击事件
    handleNodeClick(data) {
      //当点击树节点时，赋予选中的值
      this.bbmb.pid = data.id;
      this.bbmb.parentName = data.bbmc;
    },
    /*** 点击树节点+-号，触发icon改变事件 */
    changeOpenIcon(data) {
      //修改折叠展开状态
      data.open = !data.open;
      this.$refs.parentTree.store.nodesMap[data.id].expanded = !data.open;
    },
    /**窗口取消 */
    onClose() {
      this.bbmbDialog.visible = false;
    },
    /**窗口确认 */
    onConfirm() {
      //表单验证
      this.$refs.bbmbForm.validate(async (valid) => {
        if (valid) {
          let res = null;
          //判断角色ID是否为空
          if (this.bbmb.id === "") {
            //新增 //发送添加请求
            res = await dtbbApi.add(this.bbmb);
            console.log("新增请求", res);
          } else {
            console.log(this.bbmb);
            //发送修改请求
            res = await dtbbApi.update(this.bbmb);
            console.log(res);
          }
          //判断是否成功
          if (res.success) {
            this.$message.success(res.message); //刷新
            this.search(this.pageNo, this.pageSize); //关闭窗口
            this.bbmbDialog.visible = false;
          } else {
            this.$message.error(res.message);
          }
        }
      });
    },
    /*** 打开编辑窗口 */
    handleEdit(row) {
      //数据回显
      this.$objCopy(row, this.bbmb); //将当前编辑的数据复制到role对象中 //设置窗口标题
      this.bbmbDialog.title = "编辑报表模板"; //显示编辑角色窗口
      this.bbmbDialog.visible = true;
    },
    /*** 删除 */
    async handleDelete(row) {
        //确认是否删除
        let confirm = await this.$myconfirm("确定要删除该数据吗?");
        if (confirm) {
          //发送删除请求
          let res = await dtbbApi.delete({ id: row.id });
          //判断是否成功
          if (res.success) {
            //成功提示
            this.$message.success(res.message);
            //刷新
            this.search(this.pageNo, this.pageSize);
          } else {
            //失败提示
            this.$message.error(res.message);
          }
        }
    },

    /**打开选择字段窗口 */
    async selectZd(row){
      this.current = row;
      this.dialogVisible = true;
      let res = await sjzdApi.getList({lx:0});
      //执行成功
      if (res.success) {
        console.log(res.data);
        this.bbList = res.data.records;
      }
    },
    /**下拉框数据联动 */
    async changeSelect() {
      // 清空字段内容
      this.bbform.zd = ''
      // 查出所选表对应的所有字段
      let res = await sjzdApi.getList({lx:1,pid:this.bbform.id});
      //执行成功
      if (res.success) {
        console.log(res.data);
        this.zdList = res.data.records;
      }
    },
    async changeSelectZd(val){
      console.log(val);

      var arr=[];
      for(var i = 0 ; i < val.length; i++){ 
          let obj={}
          obj= this.zdList.find((item)=>{
              return item.id === val[i];
          });
          console.log(obj);
          arr.push(obj);
          
      }
      this.afterList = arr;
      
      console.log(this.afterList);

      let res = await infoApi.getList({bbid:this.current.id});
      //执行成功
      if (res.success) {
        console.log('info'+JSON.stringify(res.data.records));
        this.sjzdList = res.data.records;
      }
    },
    changeSelectSjzd(val){
      console.log(val);
      if(val==''){
          this.infoForm.cj = 1
      }else{
          console.log(this.infoForm.pid);
      let obj={}
      obj= this.sjzdList.find((item)=>{
          return item.id === val;
      });
      console.log('cj'+obj.cj);
      this.infoForm.cj = obj.cj+1;
      }
      
    },
    handleChange(){
      this.$resetForm("infoForm", this.infoForm);
    },
    async submitInfo(){
      if(this.infoForm.pid ===''){
          this.infoForm.pid ='0';
      }
      this.infoForm.bbid = this.current.id;
      console.log('form'+JSON.stringify(this.infoForm));
      let res = await infoApi.add(this.infoForm);

      console.log(res)
      //判断是否成功
      if (res.success) {
          this.$message.success(res.message);
      } else {
          console.log(res)
          this.$message.error(res.message);
      }
    },
    /**关闭窗口 */
    close(){
      this.bbform.id = '';
      this.bbform.zd = '';
      this.afterList =[];
      this.dialogVisible = false;
      this.$resetForm("infoForm", this.infoForm);
    },
    /**选择字段确认按钮 */
    async submit(){
      this.dialogVisible = false;
      console.log(this.bbform.zd);

      // let res = await infoApi.add();
      // //执行成功
      // if (res.success) {
      //   this.$message.success(res.message);
      // }
    },
    //报表预览
    handleCheck(row){
      axios({ 
          method: "get",
          responseType: "arraybuffer", // 预览arraybuffer，下载：blob
          url:"http://47.108.251.250:3296/api/dtbb/DownloadMyExcel?token=" + getToken() + '&bbdm=' + row.bbdm,
      })
      .then((res) => {
          console.log(res); // 图一
          let data = new Uint8Array(res.data); //
          let workbook = XLSX.read(data, { type: "array" });
          console.log('workbook'+workbook);
          let sheetNames = workbook.SheetNames; // 工作表名称集合
          console.log(sheetNames);
          this.workbook = workbook;        
          this.cardActive = sheetNames[0];
          console.log('cardActive'+this.cardActive);
          this.getTable(sheetNames[0]);
          this.previewFile = true;
      })
      .catch((error) => {
          this.previewFile = false;
          this.$message.error("预览失败");
      });
    },
    getTable(sheetName) {
      var worksheet = this.workbook.Sheets[sheetName];
      console.log('worksheet'+JSON.stringify(worksheet));
      this.tableau = XLSX.utils.sheet_to_json(worksheet, {
          header: 1,
          defval: "",
      }); // 直接v-for循环
      console.log(this.tableau);
    },
    //报表下载
    downloadExcel(row){
      window.open("http://47.108.251.250:3296/api/dtbb/DownloadMyExcel?token=" + getToken() + '&bbid=' + row.id);

    },

    /*** 当每页数量发生变化时触发该事件 */
    handleSizeChange(size) {
      this.pageSize = size;
      //将每页显示的数量交给成员变量
      this.search(this.pageNo, size);
    },
    /*** 当页码发生变化时触发该事件 */
    handleCurrentChange(page) {
      this.pageNo = page;
      //调用查询方法
      this.search(page, this.pageSize);
    },

    //上报
    handSubmit(row){
      this.$objCopy(row, this.bbmb);
      this.$confirm('确定上报此报表?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let res = null;
          console.log(this.bbmb.id+"111");
      
          //发送审核请求
          this.bbmb.approveBz = '';
          this.bbmb.approveStatus = 1;
          console.log(this.bbmb);
          res = await bbmbApi.updateApprove(this.bbmb);

          console.log(res)
          //判断是否成功
          if (res.success) {
              // this.$message.success(res.message);
              this.$message({ message: '修改审核状态成功！', type: 'success' });
              //刷新
              this.search();
              //关闭窗口
              this.dialogFormVisible = false;
          } else {
            console.log(res)
              this.$message.error(res.message);
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消上报'
          });          
        });

    },

    //审核
    async handAudit(row){
      this.$resetForm("bbsh", this.bbsh); //清空表单数据
      console.log(row.id);
      // this.$objCopy(row, this.bbmb);
      this.bbsh.id = row.id;
      this.dialogFormVisible = true;
    },
    // 审核弹框关闭触发
    shclose(formName) {
      this.dialogFormVisible = false;
      this.$resetForm("bbsh", this.bbsh); //清空表单数据
      // 清空表单校验，避免再次进来会出现上次校验的记录
      this.$refs[formName].clearValidate()
    },

    //审核确认
    submitForm(formName) {
      //表单验证
      this.$refs[formName].validate(async (valid) => {
          if (valid) {
              let res = null;
              console.log(this.bbsh.id+"111")
         
                  //发送审核请求
                  console.log(this.bbsh)
                  res = await bbmbApi.updateApprove(this.bbsh);

              console.log(res)
              //判断是否成功
              if (res.success) {
                  // this.$message.success(res.message);
                  this.$message({ message: '修改审核状态成功！', type: 'success' });
                  //刷新
                  this.search();
                  this.$resetForm("bbsh", this.bbsh); //清空表单数据
                  //关闭窗口
                  this.dialogFormVisible = false;
              } else {
                console.log(res)
                  this.$message.error(res.message);
              }
          }
      })
    },

  },
  //初始化时调用
  created() {
    this.search();
    this.$data.leve = sessionStorage.getItem("userLeve");
  },
  //挂载后调用
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - 220;
    });
  },
};
</script>

<style lang="scss" scoped>

.tablestyle{
    display: flex;
    justify-content: center;
    align-items: center;
}

.abow_dialog {
  display: flex;
  justify-content: center;
  align-items: Center;
  overflow: hidden;
  .el-dialog {
      margin: 0 auto !important;
      height: 90%;
      overflow: hidden;
      .el-dialog__body {
          position: absolute;
          left: 0;
          top: 54px;
          bottom: 0;
          right: 0;
          padding: 0;
          z-index: 1;
          overflow: hidden;
          overflow-y: auto;
      }
  }
}
::v-deep .saveAsDialog2 {
  width: 25% !important;
}

.el-textarea{
  width: 105%;
 }

 .tagstyle{
  cursor: pointer;
}

::v-deep .el-table .cell{
  overflow: visible;
}
</style>
